package name.sraynal.coodiary.file.analyzer;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.regex.Matcher;

import name.sraynal.coodiary.fileprovider.IConfigProvider;
import name.sraynal.coodiary.storage.Quote;

public class SvgFileAnalyzer extends ClassicFileAnalyzer {

	public SvgFileAnalyzer(IConfigProvider configProvider) {
		super(configProvider);
	}

	private Quote quote;
	private Date quoteDate;
	private static final SimpleDateFormat SVG_DATE_FORMAT = new SimpleDateFormat(
			"'Date':dd.mm.yyyy hh:mm:ss");
	private String currentId;

	@Override
	public Set<Quote> analyze(File input) throws IOException {

		FileInputStream fis = new FileInputStream(input);
		InputStreamReader isr = new InputStreamReader(fis, "UTF-16LE");
		BufferedReader br = new BufferedReader(isr);
		String read;
		int i = 0;
		while ((read = br.readLine()) != null) {
			if (i == 19) {
				try {
					this.quoteDate = SVG_DATE_FORMAT.parse(read);
				} catch (ParseException e) {
					throw new RuntimeException(e);
				}
			} else if (i == 20) {
				Matcher matcher = ComputerFileAnalyzer.QUOTE_PATTERN
						.matcher(read);
				if (!matcher.matches()) {
					System.out.println("[" + read
							+ "] does not match any pattern.");
				} else {
					String type = getCorrepondingType(matcher.group(1));
					if (type == null) {
						System.out.println("Cannot handle quote : "
								+ matcher.group(2));
					}
					this.quote = new Quote(this.quoteDate, matcher.group(2),
							type);
				}
			} else if (i == 4) {
				this.currentId = read.substring(9);
				System.out.println(this.currentId);
			}
			i++;
		}
		br.close();
		Set<Quote> quotes = new HashSet<Quote>();
		quotes.add(this.quote);
		return quotes;
	}

	@Override
	public Set<Quote> analyze(List<File> inputs) throws IOException {
		Set<Quote> result = new HashSet<Quote>();

		for (int i = 0; i < inputs.size(); i++) {
			result.addAll(analyze(inputs.get(i)));
		}
		return result;
	}

	@Override
	public Set<Quote> getQuotes() {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public void setInput(File input) {
		// TODO Auto-generated method stub

	}
}
